<?php
/**
 * 过虑
 * 
 * @package SFramework
 * @author Shuky
 * @since v1.0
 * @version $Id: Filter.php 82 2010-12-23 18:23:35Z shukyoo@gmail.com $
 */
namespace SF;

class Filter
{
    protected $_value;
    
    
    /**
     * 可以在构造的时候传入$value
     */
    public function __construct($value = null)
    {
        if (null !== $value) {
        	$this->setValue($value);
        }
    }
    
    /**
     * 设置value
     */
    public function setValue($value)
    {
    	$this->_value = $value;
    }
    
    
    /**
     * 获取value
     */
    public function getValue()
    {
    	return $this->_value;
    }
    
    
    /**
     * 聚合验证处理
     * 形式：
     * runFilter('stringToLower')
     * runFilter(array(
     *     'stringToLower',
     *     array('filter'=>'quote', 'options'=>array(1))
     * ))
     * @param string|array $rule
     */
    public function runFilter($rule)
    {
    	if (is_string($rule)) {
    		$rule = array($rule);
    	}
    	if (is_array($rule)) {
    	    foreach ($rule as $f) {
        	    if (is_string($f)) {
        	    	$f = array('filter'=>$f);
        	    }
        	    if (empty($f['filter']) || !method_exists($this, $f['filter'])) {
                    throw new SException\MethodNotExists('无效的过虑方法'. $f['filter']);
                }
                $options = array('value'=>$this->_value);
                if (isset($f['options']) && is_array($f['options'])) {
                	$options = array_merge($options, $f['options']);
                }
                $this->_value = call_user_func_array(array(__CLASS__, $f['filter']), $options);
        	}
    	}
    	return $this->_value;
    }
    
    
    /**
     * 小写
     */
	public static function stringToLower($value)
	{
		return strtolower((string)$value);
	}
	
	
	/**
	 * 大写
	 */
	public static function stringToUpper($value)
	{
		return strtoupper((string)$value);
	}
	
	
	/**
	 * trim
	 */
	public static function stringTrim($value, $char = '')
	{
		return trim($value, $char);
	}
	
	
	/**
	 * 过虑引号
	 */
	public static function deQuote($value, $q = 0)
	{
	    if ($q == 0 || $q == 1) {
	    	$value = str_replace('\'', '', $value);
	    }
	    if ($q == 0 || $q == 2) {
	    	$value = str_replace('\"', '', $value);
	    }
	    return $value;
	}
	
	
	/**
	 * basename
	 */
	public static function basename($value)
	{
		return basename((string)$value);
	}
	
	
	/**
	 * int
	 */
	public static function int($value)
	{
		return (int)$value;
	}
}